package cn.demo.rocketmq.transaction.demo1;


import cn.demo.rocketmq.transaction.demo1.util.FastJsonUtil;
import cn.demo.rocketmq.transaction.demo1.util.Order;
import cn.demo.rocketmq.transaction.demo1.util.OrderMapper;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * @author: wangsaichao
 * @date: 2018/2/12
 * @description: 订单Service层
 */
@Service
public class OrderService {

    @Autowired
    private TransactionMQProducer transactionMQProducer;

    @Autowired
    private TransactionExecuterImpl transactionExecuterImpl;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 创建订单,并发送到MQ
     *
     * @param userId
     */
//    @Transactional(rollbackFor = Exception.class)
    public void createOrder(String userId) throws Exception {

        Order order = new Order();
        order.setUserId(userId);
        order.setAmount(666D);
        order.setState(Order.PREPARED);
        order.setUserName("王赛超");
        order.setUpdateTime(new Date());
        //订单id,也是key
        String uuid = UUID.randomUUID().toString();
        order.setOrderId(uuid);

        //订单入库
        orderMapper.insert(order);

        //发送消息
        this.sendMessage(order);

        System.out.println("订单：" + uuid + "入库成功,发送消息成功");

    }

    /**
     * 给消费者发送消息
     *
     * @param order
     * @throws Exception
     */
    private void sendMessage(Order order) throws Exception {

        //构造消息数据
        Message message = new Message();
        //主题
        message.setTopic("TransactionTest");
        //子标签
        message.setTags("tagOrder");

        message.setKeys(order.getOrderId());

        message.setBody(FastJsonUtil.beanToJson(order).getBytes("utf-8"));

        //封装本地逻辑

        transactionMQProducer.sendMessageInTransaction(message, transactionExecuterImpl, 1000);

    }
}

